# -*- encoding: utf-8 -*-
import time
import sys
from osv import fields, osv
from tools.translate import _
import pdb
import logging


class Scholarship(osv.osv):
    _table = 'ctsv_danhsachhocbong'
    _name = 'ctsv.danhsachhocbong'
    _description = 'Danh sach hoc bong'
    _columns = {
        'mssv' : fields.char('MSSV', size = 64, required = True),
        'name' : fields.char('Họ tên', size = 64, required = True),
        'dtb' : fields.float('DTB', digits=(12,2)),
        'drl' : fields.integer('DRL'),
        'schol_amount' : fields.float('Số tiền', digits=(12,2)),
        'semester': fields.many2one('aas.academic.semester', string='Học kỳ'),
        'list_id': fields.many2one('ctsv.getdshb', string='Danh sách'),
        'department': fields.many2one('aas.department', string='Khoa'),
        'class_id': fields.many2one('aas.class', string='Lớp'),
        }
    _defaults = {}
    _order = 'dtb desc, drl desc'
    
    def get_all_lines(self, cr, uid, id, context=False):
        result = []
        ids = self.search(cr, uid, [('list_id', '=', id)], context=context)
        if ids:
            stt = 0
            for i in ids:
                obj = self.browse(cr, uid, i, context=context)
                stt += 1
                mssv = obj.mssv
                hoten = obj.name
                dtb = obj.dtb
                drl = obj.drl
                sotien = obj.schol_amount
                khoa = obj.department.name
                lop = obj.class_id.name
                logging.info('---- mssv, hoten : %s -- %s ', mssv, hoten)
                result.append([stt,
                               mssv,
                               hoten,
                               dtb,
                               drl,
                               sotien,
                               khoa,
                               lop,])
        return result

   
Scholarship()

class Scholarship_Operation(osv.osv):
    logging.getLoggerClass()
    
    def check_existing(self, cr, uid, semester_id, context):
        logging.info('----semester for checking scholarship existing---- : %s ', semester_id)
        if semester_id:
            cs_obj = self.pool.get('aas.course.student')
            cs_ids = cs_obj.search(cr, uid, [('course_id.academic_semester.id', '=', semester_id)], context=context)
            if not cs_ids: raise osv.except_osv(_('Thông báo!'), _("Chưa có dữ liệu điểm!"))
            existing = self.search(cr, uid, [('semester', '=', semester_id)], context=context)
            if existing: raise osv.except_osv(_('Thông báo!'), _('Đã tồn tại học bổng cho học kì này!'))
        pass
    
    
    def create(self, cr, uid, vals, context=None):
        logging.info('----Vals: %s', vals.keys())
        semester = vals.get('semester', False)
        drl = vals.get('drl', False)
        if drl > 100:
            raise osv.except_osv(_('Thông báo!'), _('Điểm rèn luyện phải nhỏ hơn 100!'))
        self.check_existing(cr, uid, semester, context=context)
        new_id = super(Scholarship_Operation, self).create(cr, uid, vals, context=context)
        logging.info('----New_Id: %s', new_id)
        return new_id
    
    def write(self, cr, uid, ids, vals, context=None):
        logging.info('----vals for update---- : %s ', vals.keys())
        drl = vals.get('drl', False)
        if drl > 100:
            raise osv.except_osv(_('Thông báo!'), _('Điểm rèn luyện phải nhỏ hơn 100!'))
        semester = vals.get('semester', False)
        self.check_existing(cr, uid, semester, context=context)
        if vals.has_key('update') == False:
            vals['update'] = True
        return super(Scholarship_Operation, self).write(cr, uid, ids, vals, context=context)
    
    def unlink(self, cr, uid, ids, context=None):
        logging.info('----ids for deleting---- : %s ', ids)
        hocbong = self.pool.get('ctsv.danhsachhocbong')
        for id in ids:
            deleted_ids = hocbong.search(cr, uid, [('list_id.id', '=', id),], context=context)
        hocbong.unlink(cr, uid, deleted_ids, context=context)
        res = super(Scholarship_Operation, self).unlink(cr, uid, ids, context=context)
        return res

    def onchange_kha(self, cr, uid, ids, kha):
        result = {'value': {}}
        gioi = int(kha)*1.2
        xuatsac = int(kha)*1.5
        result['value']['gioi'] = gioi
        result['value']['xuatsac'] = xuatsac
        return result    
    
    def get_dept_list(self, cr, uid, context):
        res = []
#        dept_id = cr.execute("select id from aas_department",())
        dept_obj = self.pool.get('aas.department')
        hbs = dept_obj.search(cr, uid, [], context=context)
        for id in hbs:
            logging.info('----------dept_id = %s',id)
            cr.execute(''' select * from res_users where dept_id = %s and student = 'TRUE' ''',(id,))
            res.append(cr.dictfetchall())
        return res 
    
    def get_class_list(self, cr, uid, context):
        res = []
        class_obj = self.pool.get('aas.class')
        hbs = class_obj.search(cr, uid, [], context=context)
        for id in hbs:
            logging.info('----------class_id = %s',id)
            cr.execute(''' select * from res_users where class_id = %s and student = 'TRUE' ''',(id,))
            res.append(cr.dictfetchall())
        return res 
    
    
    def check_pass(self, details):
        for detail in details:
            logging.info('-------Course Name: %s ,----isPassed : %s', detail[3], detail[9])
            if detail[9] == False:
                logging.info('-------Break---------')
                return False
        return True
    

    def get_scholarship_list(self, cr, uid, ids, field_name, field_value, arg, context=None):
#        cr.execute("DELETE FROM ctsv_danhsachhocbong", ())
        allStdSql = '''
                    SELECT *
                    FROM res_users
                    WHERE student = 'TRUE'
                    '''
        cr.execute(allStdSql,())
        allStudents = cr.dictfetchall()
        res={}
        records = self.browse(cr, uid, ids)
        logging.info('----records len : %s', len(records))
        user_obj = self.pool.get('res.users')
        hocbong = self.pool.get('ctsv.danhsachhocbong')
        semester_obj = self.pool.get('aas.academic.semester')
        sv_pt_obj = self.pool.get('ctsv.sinhvien.phongtrao')
        for r in records:
            logging.info('----update : %s id : %s', r.update, str(r.id))
            if(r.update):
                cr.execute("DELETE FROM ctsv_danhsachhocbong WHERE list_id = %s", (r.id,))
                logging.info('----semester : %s -----year: %s -----------type: %s', r.semester, r.semester.academic_year, r.type)
                year_id = r.semester.academic_year and r.semester.academic_year.id or False
                semester = r.semester and r.semester.id or False
#                if semester == 1: return res
#                semester_id = semester_obj.browse(cr, uid, semester - 1, context=context)
#                year_id = semester_id.academic_year and semester_id.academic_year.id or False
                fee_total = r.fee_total
                students = []
                if r.type == 'khoa' : 
                    students += self.get_dept_list(cr,uid,context)
                if r.type == 'lop' : 
                    students += self.get_class_list(cr,uid,context)
                if r.type == 'truong' :
                    students.append(allStudents)
                    
                for student in students: 
                    dept_id = 0
                    class_id = 0
                    scale = len(student);
                    if r.type == 'khoa' or r.type == 'lop' :
                        scale = (len(student)*15)/100;
                    for std in student:
                        drl = sv_pt_obj.get_drl_result(cr, uid, std['id'], semester, context=context)
                        logging.info('----DRL of %s : %s  ', std['code'], drl)
                        stdrs = user_obj.get_study_result(cr, uid, std['id'], year_id, semester, mode='full', context=context)
                        logging.info('----Total credit : %s ---std id: %s',stdrs['total_credit'],std['code'])
                        logging.info('----stdr : %s ',stdrs['details'])
                        if stdrs['details'].has_key(r.semester.academic_year.name):
                            if(self.check_pass(stdrs['details'][r.semester.academic_year.name][r.semester.name]) and drl >= r.drl):
                                if (stdrs['gpa'] >= r.dtb and stdrs['total_credit'] >= r.total_credit) :
                                    schol_amount = r.kha
                                    if (stdrs['gpa'] >= 9) :
                                        schol_amount = r.xuatsac
                                    else :
                                        if (stdrs['gpa'] >= 8) :
                                            schol_amount = r.gioi
                                    vals = {
                                            'mssv' : std['code'],
                                            'name' : std['name'],
                                            'dtb' : stdrs['gpa'],
                                            'drl' : drl,
                                            'schol_amount' : schol_amount,
                                            'semester' : r.semester.id,
                                            'list_id' : r.id,
                                            'department' : std['dept_id'],
                                            'class_id' : std['class_id'], 
                                            }
                                    dept_id = std['dept_id']
                                    class_id = std['class_id']
                                    logging.info('----------class_id 2 = %s',class_id)
                                    hocbong.create(cr, uid, vals, context=context)
                    
                    if r.type == 'khoa' :         
                        hbs = hocbong.search(cr, uid, [('semester', '=', r.semester.id), ('department', '=', dept_id)], context=context)
                    if r.type == 'lop' :         
                        hbs = hocbong.search(cr, uid, [('semester', '=', r.semester.id), ('class_id', '=', class_id)], context=context)
                    if r.type == 'truong' :
                        hbs = hocbong.search(cr, uid, [('semester', '=', r.semester.id)], context=context)
                    logging.info('----------hbs = %s',hbs)
                    logging.info('----rowcount: %s ----scale: %s',len(student),scale);
                    deleted_ids = []
                    for h in hocbong.browse(cr,uid,hbs,context=context) :
                        if fee_total > 0 and scale > 0 :
                            fee_total = fee_total - h.schol_amount
                            scale = scale - 1
                        else:
                            deleted_ids.append(h.id)
                    hocbong.unlink(cr, uid, deleted_ids, context=None)      
                            
            cr.execute("SELECT * FROM ctsv_danhsachhocbong",())
            dshb = cr.dictfetchall()
            for hb in dshb :
                if r.id == hb['list_id']: 
                    res[r.id] = hb['id']
            self.write(cr, uid, [r.id], {'update': False,}, context=None)
        return res            




    def get_scholarship(self, cr, uid, id, semester, dtb, total_credit, fee_total, type, kha, xuatsac, gioi, context=None):
        cr.execute("DELETE FROM ctsv_danhsachhocbong", ())
        allStdSql = '''
                    SELECT *
                    FROM res_users
                    WHERE student = 'TRUE'
                    '''
        cr.execute(allStdSql,())
        allStudents = cr.dictfetchall()
        res={}
        user_obj = self.pool.get('res.users')
        hocbong = self.pool.get('ctsv.danhsachhocbong')
        logging.info('----semester : %s -----year: %s -----------type: %s', semester, semester.academic_year, type)
        year_id = semester.academic_year and semester.academic_year.id or False
        semester_id = semester and semester.id or False
        students = []
        if type == 'khoa' : 
            students += self.get_dept_list(cr,uid,context)
        if type == 'truong' :
            students.append(allStudents)
                
        for student in students: 
            dept_id = 0;
            scale = len(student);
            if type == 'khoa' :
                scale = (len(student)*15)/100;
            logging.info('----rowcount: %s ----scale: %s',len(student),scale);
            for std in student:
                stdrs = user_obj.get_study_result(cr, uid, std['id'], year_id, semester_id, mode='full', context=context)
                logging.info('----Total credit : %s ',stdrs['total_credit'])
                if (stdrs['gpa'] >= dtb and stdrs['total_credit'] >= total_credit) :
                    schol_amount = kha
                    if (stdrs['gpa'] >= 9) :
                        schol_amount = xuatsac
                    else :
                        if (stdrs['gpa'] >= 8) :
                            schol_amount = gioi
                    vals = {
                            'mssv' : std['code'],
                            'name' : std['name'],
                            'dtb' : stdrs['gpa'],
                            'drl' : 70,
                            'schol_amount' : schol_amount,
                            'semester' : semester.id,
                            'list_id' : id,
                            'department' : std['dept_id'],
                            }
                    dept_id = std['dept_id'];
                    hocbong.create(cr, uid, vals, context=context)
                
            if type == 'khoa' :         
                hbs = hocbong.search(cr, uid, [('semester', '=', semester.id), ('department', '=', dept_id)], context=context)
            if type == 'truong' :
                hbs = hocbong.search(cr, uid, [('semester', '=', semester.id)], context=context)
            deleted_ids = []
            for h in hocbong.browse(cr,uid,hbs,context=context) :
                if fee_total > 0 and scale > 0 :
                    fee_total = fee_total - h.schol_amount
                    scale = scale - 1
                else:
                    deleted_ids.append(h.id)
            hocbong.unlink(cr, uid, deleted_ids, context=None)      
                        
        cr.execute("SELECT * FROM ctsv_danhsachhocbong",())
        dshb = cr.dictfetchall()
        for hb in dshb :
            if id == hb['list_id']: 
                res[id] = hb['id']
        return res     
    
    def default_semester(self, cr, uid, context=False):
        semester_id = 0
        now = time.strftime('%m/%d/%Y')
        logging.info('------- now for semester default:  %s',now)
        week_obj = self.pool.get('aas.academic.week')
        ids = week_obj.search(cr, uid, [('date_end', '>=', now), ('date_start', '<=', now)], context=context)
        logging.info('----week ids : %s',ids)
        if ids:
            obj = week_obj.browse(cr, uid, ids[0], context=context)
            semester_id = obj.academic_semester.id or False
        return semester_id       
   
    _table = 'ctsv_getdshb'
    _name = 'ctsv.getdshb'
    _description = 'Dieu kien xet hoc bong'
    _columns = {
        'name' : fields.char('Tên ds', size = 64, required = True),
        'fee_total' : fields.float('Tổng số tiền cấp học bổng', digits=(12,2), required = True),
        'drl' : fields.integer('Điểm rèn luyện tối thiểu', required = True),
        'dtb' : fields.float('Điểm trung bình tối thiểu', digits=(12,2), required = True),
        'total_credit' : fields.integer('Tổng sồ tín chỉ tối thiểu', required = True),
        'kha' : fields.float('Loại khá', digits=(12,2), required = True),
        'gioi' : fields.float('Loại giỏi', digits=(12,2), required = True),
        'xuatsac' : fields.float('Loại xuất sắc', digits=(12,2), required = True),
        'semester': fields.many2one('aas.academic.semester', string='Áp dụng cho học kỳ', required = True),
        'type': fields.selection((('truong', _('Xét theo trường')),
                                 ('khoa', _('Xét theo 15% khoa')),
                                 ('lop', _('Xét theo 15% lớp'))), string='Cách xét', required = True),
        'update': fields.boolean('', readonly=True),
        'students': fields.function(get_scholarship_list, type='one2many', obj='ctsv.danhsachhocbong',
                                     readonly=True, method=True, string='Details'), 
    }
    _defaults = {
        'name': lambda *a: 'named',
        'fee_total': lambda *a: 15000000,
        'drl': lambda *a: 70,
        'dtb': lambda *a: 7,
        'total_credit': lambda *a: 15,
        'kha': lambda *a: 1000000,
        'gioi': lambda *a: 1500000,
        'xuatsac': lambda *a: 2000000,
        'update': lambda *a: True,
        'semester': default_semester,
    }
    
    def get_all_lines(self, cr, uid, id, context=None):
        result = []
        obj = self.browse(cr, uid, id, context=context)
        if obj:
            stt = 0
            for std in obj.students:
                stt += 1
                mssv = std.mssv
                hoten = std.name
                dtb = std.dtb
                drl = std.drl
                sotien = std.schol_amount
                khoa = std.department
                result.append([stt,
                               mssv,
                               hoten,
                               dtb,
                               drl,
                               sotien,])
        return result

Scholarship_Operation()


class scholarship_list(osv.TransientModel):
    _name = 'ctsv.dshb.list'
    _columns = {
        'hocbong_ids': fields.many2many('ctsv.danhsachhocbong', 'dshb_list_rel', 'ds_id', 'hb_id', string='Danh sách học bổng'),
        'readonly': fields.boolean('', readonly=True),
    }
    _defaults = {  
        'readonly': lambda *a: True,
    }
    
    def default_get(self, cr, uid, fields, context=False):
        res = super(scholarship_list, self).default_get(cr, uid, fields, context=context)
        id = context.get('active_id', False)
        logging.info('---- ACTIVE ID:  %s',id)
        self.list_id = False
        if id:
            list_obj = self.pool.get('ctsv.danhsachhocbong')
            ids = list_obj.search(cr, uid, [('list_id', '=', id)], context=context)
            logging.info('------- ids rel:  %s',ids)
            res.update({'hocbong_ids': ids})
            
            if ids:
                sql = '''
                    SELECT list_id
                    FROM ctsv_danhsachhocbong
                    WHERE id = %s
                '''
                cr.execute(sql, (ids[0],))
                if cr.rowcount > 0:
                    self.list_id = cr.fetchone()[0]
        return res
    
    
    def print_report(self, cr, uid, ids, context=False):
        datas = {}
        if not self.list_id:
            raise osv.except_osv(_('Thông báo!'), _("Không thể tải bản in!"))
        logging.info('------- list_id rel:  %s',self.list_id)
        datas['id'] = self.list_id
        datas['ids'] = [self.list_id]
        datas['model'] = 'ctsv.danhsachhocbong'
        logging.info('------- data rel:  %s',datas)
        return {
            'type': 'ir.actions.report.xml', 
            'report_name': 'ctsv_scholarship_report', 
            'datas': datas
        }
    
scholarship_list()
           
